package edu.pku.sei.transformation.qvt.action;

import java.io.FileWriter;
import java.io.IOException;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.transformation.editor.model.AtomicTransformation;
import edu.pku.sei.transformation.editor.views.icons.IconsProvider;
import edu.pku.sei.transformation.qvt.adapter.TransformationAdapter;
import edu.pku.sei.transformation.qvt.codegen.QVTGenerator;

public class GenQVTAction extends Action {
	private AtomicTransformation transformation;
	public GenQVTAction(AtomicTransformation t) {
		this.transformation = t;
		setText("generate qvt fle");
		setImageDescriptor(IconsProvider.getImageDescriptor(IconsProvider.FILE_EXPORT_ICO));
	}
	@Override
	public void run() {
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
		.getShell();
		FileDialog dialog = new FileDialog(shell, SWT.SAVE); 
		dialog.setFileName(transformation.getName()+".qvt");
		String addr = dialog.open();
		if (addr==null)
			return;
		QVTGenerator generator = new QVTGenerator();
		String content = generator.generate(new TransformationAdapter(transformation));
		
		FileWriter fw;
		try {
			fw = new FileWriter(addr);
			fw.write(content, 0, content.length());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
